/*
 * @Author: sean_kei@163.com
 * @Date: 2021-06-08 15:07:38
 * @LastEditors: sean_kei@163.com
 * @LastEditTime: 2022-08-04 13:29:58
 */
package com.wxhandle.cleandemo.core.domain.identity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;

import com.wxhandle.cleandemo.core.events.RoleChangedEvent;

import org.springframework.data.domain.AbstractAggregateRoot;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@RequiredArgsConstructor
@Entity
public class SysRole extends AbstractAggregateRoot<SysRole> implements Serializable{
    @Id
    @Column(name = "id", length = 25, nullable = false)
    private String id;

    @Column(name = "description", length = 50, nullable = false)
    private String description;


    //引用的权限实体对象集合
    @ManyToMany(cascade = CascadeType.PERSIST,fetch = FetchType.LAZY)
    @JoinTable(name = "SysRoleClaim",
    joinColumns = {@JoinColumn(name = "roleId")},
    inverseJoinColumns = {
        @JoinColumn(name="claimId",insertable=false, updatable=false),
        @JoinColumn(name="serviceId",insertable=false, updatable=false)})
    private List<SysClaim> claims;

    public void UpdatePermissions(List<SysClaim> claims){
        if(null == this.getClaims())
            this.setClaims(new ArrayList<>());

        getClaims().forEach(c-> {
                if(!claims.contains(c)){
                    getClaims().remove(c);
                }else{
                    claims.remove(c);
            }
        });
        this.getClaims().addAll(claims);
        RoleChangedEvent event = new RoleChangedEvent();
        event.setId(getId());
        event.setClaims(getClaims());
        registerEvent(event);
    }
}
